package body

import (
	"errors"
	"gitcode.com/G-YT/ANN/server/global"
	"gitcode.com/G-YT/ANN/server/model/body"
	bodyRes "gitcode.com/G-YT/ANN/server/model/body/response"
	"gitcode.com/G-YT/ANN/server/model/system"
	"gorm.io/gorm"
	"strconv"
	"strings"
)

type BodyService struct {
}

// GetHealthManageTagByUid 获取用户健康管理标签
func (bodyService *BodyService) GetHealthManageTagByUid(uid, types uint) (hmt body.HealthManageTag, err error) {
	err = global.GVA_DB.Where("uid = ? AND types = ?", uid, types).First(&hmt).Error
	return hmt, err
}

// GetHealthManageList 获取疼痛方案数据
func (bodyService *BodyService) GetHealthManageList() (bh []bodyRes.HealthManage, err error) {
	err = global.GVA_DB.Model(&body.HealthManage{}).Preload("Ttdcount", "class = 2 AND types = 2").Where("types = ?", 2).Find(&bh).Error
	return
}

// GetBodyBalanceInfo 获取身体平衡数据
func (bodyService *BodyService) GetBodyBalanceInfo() (bh []bodyRes.BodyBalance, err error) {
	err = global.GVA_DB.Model(&body.HealthManage{}).Preload("BbcInfo", "class = 2 AND types = 1").Where("types = ?", 1).Find(&bh).Error
	return
}

// GetFasciaChainInfo 获取筋膜链数据
func (bodyService *BodyService) GetFasciaChainInfo() (bh []body.HealthManage, err error) {
	err = global.GVA_DB.Model(&body.HealthManage{}).Where("types = ?", 3).Find(&bh).Error
	return
}

// GetPainLevelList 获取疼痛等级列表
func (bodyService *BodyService) GetPainLevelList() (sysDictionaryDetails []system.SysDictionaryDetail, err error) {
	err = global.GVA_DB.Model(&system.SysDictionaryDetail{}).Where("sys_dictionary_id = 8").Find(&sysDictionaryDetails).Error
	return sysDictionaryDetails, err
}

// GetPainLevelDetail 获取单条疼痛等级详情数据
func (bodyService *BodyService) GetPainLevelDetail(value uint) (sysDictionaryDetail system.SysDictionaryDetail, err error) {
	err = global.GVA_DB.Where("value = ? AND sys_dictionary_id = 8", value).First(&sysDictionaryDetail).Error
	return
}

// CreateHealthManageTag 创建用户健康管理标签
func (bodyService *BodyService) CreateHealthManageTag(bh *body.HealthManageTag) (err error) {
	err = global.GVA_DB.Create(bh).Error
	return err
}

// UpdateHealthManageTag 更新用户健康管理标签
func (bodyService *BodyService) UpdateHealthManageTag(id uint, bh *body.HealthManageTag) (err error) {
	err = global.GVA_DB.Model(&body.HealthManageTag{}).Where("id = ?", id).Updates(bh).Error
	return err
}

// GetHisBalancePlan 获取用户平衡方案
func (bodyService *BodyService) GetHisBalancePlan(id string) (list bodyRes.BodyBalanceResponse, err error) {
	var hmt body.HealthManageTag
	// 获取用户平衡方案数据
	global.GVA_DB.Where("uid = ? AND types = 1", id).First(&hmt)
	// 获取所有身体平衡一二级数据
	var bb []bodyRes.BodyBalance
	if bberr := global.GVA_DB.Model(&body.HealthManage{}).Preload("BbcInfo", "class = 2 AND types = 1").Where("types = ?", 1).Find(&bb).Error; bberr != nil {
		return list, bberr
	}
	// 获取所有筋膜链数据
	var bh []body.HealthManage
	if bherr := global.GVA_DB.Model(&body.HealthManage{}).Where("types = ?", 3).Find(&bh).Error; bherr != nil {
		return list, bherr
	}
	// 创建新身体平衡返回结构体
	newBodyBalanceList := make([]bodyRes.BodyBalance, 0)
	// 创建新筋膜链返回结构体
	newFasciaChainList := make([]bodyRes.FasciaChain, 0)
	for _, v := range bb {
		newChildList := make([]bodyRes.BodyBalanceChild, 0)
		for _, value := range v.BbcInfo {
			selectedNum := selected(hmt.Place, value.ChildID)
			child := bodyRes.BodyBalanceChild{
				ChildID: value.ChildID,
				Text:    value.Text,
				Select:  selectedNum,
			}
			newChildList = append(newChildList, child)
		}
		v.BbcInfo = newChildList
		newBodyBalanceList = append(newBodyBalanceList, v)
	}
	for _, va := range bh {
		status := selected(hmt.FasciaChain, va.ID)
		FasciaChain := bodyRes.FasciaChain{
			ID:     va.ID,
			Name:   va.Name,
			Select: status,
		}
		newFasciaChainList = append(newFasciaChainList, FasciaChain)
	}
	list = bodyRes.BodyBalanceResponse{
		BbList:       newBodyBalanceList,
		FcList:       newFasciaChainList,
		Other:        hmt.Other,
		CorrectCycle: hmt.CorrectCycle,
	}
	return
}

// GetBodyBalancePage 获取身体平衡页面
func (bodyService *BodyService) GetBodyBalancePage(id uint) (list bodyRes.BodyBalanceResponse, err error) {
	// 获取用户平衡方案数据
	var bb body.HealthManageTag
	err = global.GVA_DB.Where("uid = ? AND types = 1", id).First(&bb).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return list, errors.New("請聯絡健管師提供筋膜方案")
	}
	// 解析部位ID和部位疼痛ID
	newBodyBalanceList := make([]bodyRes.BodyBalance, 0)
	placeTypesIDs := strings.Split(bb.PlaceTypes, ",")
	for _, placeTypeID := range placeTypesIDs {
		var healthManage body.HealthManage
		err = global.GVA_DB.Where("ID = ?", placeTypeID).Preload("HealthManageChilds").First(&healthManage).Error
		posture := bodyRes.BodyBalance{
			ID:      healthManage.ID,
			Name:    healthManage.Name,
			BbcInfo: make([]bodyRes.BodyBalanceChild, 0),
		}
		placeIDs := strings.Split(bb.Place, ",")
		for _, placeID := range placeIDs {
			for _, child := range healthManage.HealthManageChilds {
				if strconv.Itoa(int(child.ID)) == placeID {
					symptom := bodyRes.BodyBalanceChild{
						ChildID: child.ID,
						Text:    child.Name,
					}
					posture.BbcInfo = append(posture.BbcInfo, symptom)
				}
			}
		}
		newBodyBalanceList = append(newBodyBalanceList, posture)
	}
	newFasciaChainList := make([]bodyRes.FasciaChain, 0)
	FasciaChainIDs := strings.Split(bb.FasciaChain, ",")
	for _, v := range FasciaChainIDs {
		var fc body.HealthManage
		err = global.GVA_DB.Where("ID = ?", v).Preload("HealthManageChilds").First(&fc).Error
		fascia := bodyRes.FasciaChain{
			ID:   fc.ID,
			Name: fc.Name,
		}
		newFasciaChainList = append(newFasciaChainList, fascia)
	}
	list = bodyRes.BodyBalanceResponse{
		BbList:       newBodyBalanceList,
		FcList:       newFasciaChainList,
		Other:        bb.Other,
		CorrectCycle: bb.CorrectCycle,
	}
	return
}

func selected(ids string, id uint) int {
	ids = strings.Trim(ids, "[]")

	idSlice := strings.Split(ids, ",")

	idStr := strconv.Itoa(int(id))

	for _, v := range idSlice {
		if v == idStr {
			return 1
		}
	}
	return 2
}
